import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw, RouteLocationNormalized, NavigationGuardNext } from "vue-router";

import componentCommunication from "./modules/componentCommunication";
import lifeCycle from "./modules/lifeCycle";
import setup from "./modules/setup";
import appComponent from "./modules/appComponent";
import refReactive from "./modules/refReactive";
import watchComputed from "./modules/watchComputed";
import isKeepAlive from "./modules/isKeepAlive";
import useMixin from "./modules/useMixin";
import useRoute from "./modules/useRoute";
import slot from "./modules/slot";
import pinia from "./modules/pinia";
import echarts from "./modules/echarts";

let routes: Array<RouteRecordRaw> = [];

// 创建 Vue Router 实例
const router = createRouter({
    // createWebHashHistory 内部使用了 hash 模式
    // createWebHistory 内部使用了 history 模式
    // createMemoryHistory 内部使用了 memory 模式 无法使用浏览器的前进后退按钮
    history: createWebHashHistory(),
    routes,
});

let asyncRoutes: Array<RouteRecordRaw> = [
    ...componentCommunication,
    ...lifeCycle,
    ...setup,
    ...appComponent,
    ...refReactive,
    ...watchComputed,
    ...isKeepAlive,
    ...useMixin,
    ...useRoute,
    ...slot,
    ...pinia,
    ...echarts,
];

export async function resetRouter() {
    asyncRoutes.forEach((route) => {
        routes.push(route);
        router.addRoute(route);
    });
}

router.beforeEach((to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
    console.log("beforeEach", { to, _from });
    if (to.path === "/") {
        next({ path: "/communication/parentToChild" });
    } else {
        next();
    }
});

router.afterEach((to: RouteLocationNormalized, _from: RouteLocationNormalized) => {
    console.log("afterEach", { to, _from });
    document.title = typeof to.meta.title === "string" ? to.meta.title : "Vue Admin Box";
});

export default router;
